package com.crud.generator.model;

import lombok.Data;
import lombok.Builder;
import lombok.NoArgsConstructor;
import lombok.AllArgsConstructor;

/**
 * 字段元数据
 */
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class ColumnMetadata {
    
    /** 字段名 */
    private String columnName;
    
    /** 字段注释 */
    private String columnComment;
    
    /** 数据类型 */
    private String dataType;
    
    /** Java类型 */
    private String javaType;
    
    /** 字段长度 */
    private Integer length;
    
    /** 小数位数 */
    private Integer scale;
    
    /** 是否为空 */
    private Boolean nullable;
    
    /** 是否主键 */
    private Boolean primaryKey;
    
    /** 是否自增 */
    private Boolean autoIncrement;
    
    /** 默认值 */
    private String defaultValue;
    
    /** Java字段名(驼峰命名) */
    private String javaFieldName;
    
    /** Java属性名(首字母大写) */
    private String javaPropertyName;
    
    /**
     * 获取Java字段名(驼峰命名)
     */
    public String getJavaFieldName() {
        if (javaFieldName != null) {
            return javaFieldName;
        }
        return toCamelCase(columnName);
    }
    
    /**
     * 获取Java属性名(首字母大写)
     */
    public String getJavaPropertyName() {
        if (javaPropertyName != null) {
            return javaPropertyName;
        }
        String camelCase = toCamelCase(columnName);
        return camelCase.substring(0, 1).toUpperCase() + camelCase.substring(1);
    }
    
    /**
     * 设置Java字段名
     */
    public void setJavaFieldName(String javaFieldName) {
        this.javaFieldName = javaFieldName;
    }
    
    /**
     * 设置Java属性名
     */
    public void setJavaPropertyName(String javaPropertyName) {
        this.javaPropertyName = javaPropertyName;
    }
    
    /**
     * 下划线转驼峰
     */
    private String toCamelCase(String str) {
        if (str == null || str.isEmpty()) {
            return str;
        }
        
        StringBuilder result = new StringBuilder();
        boolean toUpper = false;
        
        for (char c : str.toCharArray()) {
            if (c == '_') {
                toUpper = true;
            } else {
                if (toUpper) {
                    result.append(Character.toUpperCase(c));
                    toUpper = false;
                } else {
                    result.append(Character.toLowerCase(c));
                }
            }
        }
        
        return result.toString();
    }
}